import {Component, Inject, OnInit} from '@angular/core';
import {_HttpClient} from '@delon/theme';
import {Router} from '@angular/router';
import {UtilityService} from '../../../service/utils.service';
import {appConfig} from '../../../service/common';
import {AppliaModule} from '../../../service/common.module';
import {NzModalService, NzNotificationService} from 'ng-zorro-antd';
import {Observable} from 'rxjs/Observable';
import {CommondictServe} from '../../../service/commonDict';
import {DA_SERVICE_TOKEN, ITokenService} from '@delon/auth';

@Component({
  selector: 'app-application',
  templateUrl: './application.component.html',
  styleUrls: ['./application.component.less']
})
export class ApplicationComponent implements OnInit {

    constructor(
        private http: _HttpClient,
        private router: Router,
        private utilityService: UtilityService,
        private modal: NzModalService,
        private nznot: NzNotificationService,
        private commondict: CommondictServe,
        @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
    ) {

    }

    appItem: AppliaModule = new AppliaModule(); // 搜索值
    appAdd: AppliaModule = new AppliaModule(); // 新增内容
    loading = false;
    isEdit = false; // 是否是修改，默认不是
    isShowinport = false; // 验证端口是否是数字
    isShowbranch = false; // 验证端口是否是是url类型
    isSlash = false; // 验证服务
    isappcodeSlash = false; // 验证服务
    artfmsg = '只能输入数字类型'
    // 应用类型
    appType: any;
    pageIndex = 1; // 当前页数
    appTitle: string;
    // 是否开通
    isOpen: any;
    modalVisible = false;
    /* 补充说明 */
    expandForm = false;
    data: any[] = []; // 表格数据
    ischange:boolean; // 取消用值
    selectedRows: any; // 总数
    headerData = [  // 配置表头内容
        { value: '应用名称', key: 'appName', isclick: true },
        { value: '应用代码', key: 'appCode', isclick: false },
        { value: '应用类型', key: 'appType', isclick: false },
        { value: '是否开通', key: 'isopen', isclick: false },
        { value: '访问地址', key: 'url', isclick: false },
        { value: 'Ip地址', key: 'ipAddr', isclick: false },
        { value: '端口', key: 'ipPort', isclick: false },
        { value: '应用描述', key: 'appCopyDesc', isclick: false },
    ];
    // 传入按钮层
    moreData = {
        morebutton: true,
        buttons: [
            { key: 'Overview', value: '查看概况' }
        ]
    }

    buttons = [
        {key: 'add', value: '新增属性', buttonCode: appConfig.funcObject.app.addFuncAttr}
    ];

    test: string;
    page: any;
    total: number;

    configTitle: any;
    funcBhvList: any; // 后台返回的行为列表
    ngOnInit() {
        this.getData(); // 只会触发一次，但是ngchanges并不会触发咋办
        this.ischange = false;
        this.configTitle = {value: '修改', buttonCode: appConfig.funcObject.app.appEdit}
        this.dictQueryKey();
        this.funcBhvList = this.tokenService.get().funcList;
    }


    // 根据key查询业务字典
    dictQueryKey() {
        this.commondict.queryDictKey(appConfig.dictKeyList.appType)
            .subscribe((val) => {
                console.log(val.result)
                this.appType = val.result;
            })

        this.commondict.queryDictKey(appConfig.dictKeyList.dictYon)
            .subscribe((val) => {
                this.isOpen = val.result;
            })
    }



    // 父组件初始化数据
    getData(options?) { // 初始化请求后台数据
        if (options) {
            this.pageIndex = 1;
        }
        this.page = {
            condition: this.objJson, // 搜索内容
            page: {
                current: this.appItem.pi,
                size: this.appItem.size,
            }
        };
        this.utilityService.postData(appConfig.serverUrl + appConfig.API.appList, this.page)
            .subscribe(
                (val) => {
                    for (let i = 0; i < val.result.records.length; i++ ) {
                        if (val.result.records[i].isopen ===  '是') {
                            val.result.records[i].buttonData = [ {key: 'dels', value: '删除', if: false, buttonCode: appConfig.funcObject.app.appDel}, {key: 'close', value: '关闭', if: false, buttonCode: appConfig.funcObject.app.appClose}, {key: 'API', value: '查看API', if: false, buttonCode: appConfig.funcObject.app.appApi}];
                        } else {
                            val.result.records[i].buttonData = [ {key: 'dels', value: '删除', if: false, buttonCode: appConfig.funcObject.app.appDel}, {key: 'open', value: '开启', if: false, buttonCode: appConfig.funcObject.app.appOpen}, {key: 'API', value: '查看API', if: false, buttonCode:  appConfig.funcObject.app.appApi}];
                        }

                        if(val.result.records[i].appDesc.length > 20) {
                            var str = val.result.records[i].appDesc;
                            val.result.records[i].appCopyDesc = str.substr(0, 10) + '...'+ str.substr(str.length - 10, str.length);
                        }else {
                            val.result.records[i].appCopyDesc = val.result.records[i].appDesc;
                        }
                    }
                    this.data = val.result.records;
                    this.total = val.result.total;
                }
            );
    }

    // 列表组件传过来的内容
    addHandler(event) {
        this.isShowinport = false;
        this.isShowbranch = false;
        this.isSlash = false;
        this.isappcodeSlash = false;
        this.ipchanges(); // 调用方法
        this.urlName(); // 验证服务名称
        setTimeout(_ => {
            this.appAdd.isOpen = 'N'; // 默认关闭
        }, 100);
        if (event === 'add') {
            for (const key in this.appAdd) {
                delete this.appAdd[key];
            }
            this.modalVisible = true;  // 此时点击了列表组件的新增，打开模态框
            this.isEdit = false;
            this.appTitle = '新增应用';
        } else { // 代表修改，把修改的内容传递进去，重新渲染
            if(event.appType === '远程') {
                event.appType = 'remote';
            } else {
                event.appType = 'local';
            }
            this.appAdd = event;
            this.modalVisible = true;  // 此时点击了列表组件的新增，打开模态框
            this.isEdit = true;
            this.appTitle = '修改应用';
        }
    }

    // 验证是否重复
    AppCodeexit(appType, appCode) {
        if(appType === '新增应用') {
            let objJson = {
                guid: '',
                appCode: appCode
            }
            this.utilityService.postData(appConfig.serverUrl  + appConfig.API.existAddAppCode , objJson)
                .subscribe(
                    (sus) => {
                        if (sus.result) {
                            this.isappcodeSlash = true; // 重复
                        } else {
                            this.isappcodeSlash = false; // 不重复
                        }
                    },
                    (error) => {
                        this.nznot.create('error', error.msg , error.msg);
                    }
                );
        } else {
            let objJson = {
                guid: this.appAdd.guid,
                appCode: appCode
        }
            this.utilityService.postData(appConfig.serverUrl  + appConfig.API.existUpdateAppCode , objJson)
                .subscribe(
                    (sus) => {
                        if (sus.result) {
                            this.isappcodeSlash = true; // 重复
                        } else {
                            this.isappcodeSlash = false; // 不重复
                        }
                    },
                    (error) => {
                        this.nznot.create('error', error.msg , error.msg);
                    }
                );
        }
    }
    // 列表传入的翻页数据
    monitorHandler(event) {
        this.pageIndex = event;
        this.getData();
    }

    // 接受子组件删除的数据 单条还是多条
    deleatData(event) {
        this.modal.open({
            title: '是否删除',
            content: '您是否确认删除所选应用?',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                this.utilityService.deleatData(appConfig.serverUrl + appConfig.API.appDed + '/' + event.guid)
                    .subscribe(
                        (val) => {
                            this.nznot.create('success', val.msg , val.msg);

                            if ( !(( this.total - 1) % 10)) {
                                // if ( !(( this.total - this.acfundata.length) % 10)) { // 支持批量删除的方法
                                this.appItem.pi -- ;
                                this.getData();
                            }

                            this.getData();
                        },
                        response => {
                            this.getData();
                        });
            },
            onCancel: () => {

            }
        });

    }

    // 批量删除
    deleteBatch(event) {
        this.modal.open({
            title: '是否删除',
            content: '您是否确认删除这' + event.length + '条应用吗?',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                let delarray = [];
                for( let i = 0; i < event.length; i++) {
                    delarray.push(event[i].guid);
                }
                let deletaObj = {
                    deleteList: delarray
                }
                this.utilityService.postData(appConfig.serverUrl + appConfig.API.batchDeleteApp, deletaObj )
                    .subscribe(
                        (val) => {
                            this.getData()
                            this.selectedRows = []
                            this.nznot.create('success', val.msg , val.msg);
                        },
                        (error) => {
                            this.nznot.create('error', error.msg , error.msg);
                        });
            },
            onCancel: () => {
                this.selectedRows = []
                this.getData()
            }
        });
    }

    // 按钮点击事件
    buttonEvent(event) {
       if (event.names.key === 'close') { // 关闭状态，调用开启逻辑
           this.utilityService.putData(appConfig.serverUrl + appConfig.API.stopApp + '/' + event.guid)
               .subscribe(
                   (val) => {
                       this.nznot.create('success', val.msg , val.msg);
                       this.getData();
                   },
                   (error) => {
                       this.nznot.create('error', error.msg , error.msg);
                       this.getData();
                   });
       } else if (event.names.key === 'open') {
           this.utilityService.putData(appConfig.serverUrl + appConfig.API.openApp + '/' + event.guid)
               .subscribe(
                   (val) => {
                       this.nznot.create('success', val.msg , val.msg);
                       this.getData();
                   },
                   (error) => {
                       this.nznot.create('error', error.msg , error.msg);
                       this.getData();
                   });
       } else if (event.names.key === 'API') {
           this.router.navigate(['interurl'],
               { queryParams:
                       { appGuid: event.guid
                       }
               });
       } else {
            this.deleatData(event);
       }
     }
    // 列表按钮方法
    buttonDataHandler(event) {
        console.log(event); // 根据event.value来判断不同的请求，来获取结果和方法或者进行路由的跳转
        if (event.value === 'Authority') {
        }

        if (event.value === 'Overview') {
        }

    }



    // 处理行为代码，跳转、弹出框、其他交互
    isActive(event) {
        let AppCode = appConfig.funcObject.app.appTab;
        if(this.funcBhvList.indexOf(AppCode) >= 0) {
            // 路由跳转 跳转到对应的功应用页
            this.router.navigate(['function'],
                { queryParams:
                        { productId: event.guid
                        }
                });
        } else {
            this.nznot.create('error', '无法跳转' , '您可能暂时没有权限');
        }

    }


    selectedRow(event) { // 选中方法，折叠层按钮显示方法

    }


    objJson = {};
    // 搜索框
    search() {
        this.objJson = this.appItem;
        this.getData(this.appItem);
    }


    reset() {
        this.appItem = new AppliaModule();
        this.objJson = {};
        this.getData();
    }
    result(){
        this.getData();
        this.ischange = true;
        this.modalVisible = false;

    }

    // 弹出框保存组件
    save() {
        if(!this.ischange){
            const jsonOption = this.appAdd;
            // 枚举值转换
            if (!this.isEdit) {
                this.utilityService.postData(appConfig.serverUrl + appConfig.API.acappAdd, jsonOption)
                    .subscribe(
                        (val) => {
                            this.nznot.create('success', val.msg , val.msg);
                            this.getData();
                        },
                        (error) => {
                            this.nznot.create('error', error.msg , error.msg);
                            this.getData();
                        });
            } else {
                this.utilityService.putData(appConfig.serverUrl + appConfig.API.appDed, jsonOption)
                    .subscribe(
                        (val) => {
                            this.nznot.create('success', val.msg , val.msg);
                            this.getData();
                        },
                        (error) => {
                            this.nznot.create('error', error.msg , error.msg);
                            this.getData();
                        });
            }

            this.modalVisible = false;
        }
    }



    checkipPort(item, status) {
        let MOBILE_REGEXP =  /^([0-9]){1,5}$/; // 验证数字的正则
        if (MOBILE_REGEXP.test(item) === true ) {
            this.isShowinport = false;
        } else {
            this.isShowinport = true;
            this.artfmsg = '只能输入数字类型,并且不能超过5位数';
        }
    }


    // 验证ip地址
    ipchanges() {
        const change = document.getElementById( 'ipaddrs');
        const change$ = Observable.fromEvent(change, 'keyup').pluck('target', 'value').debounceTime(600);
        change$.subscribe((val: any)  => {
            let MOBILE_REGEXP =/^(?:(?:1[0-9][0-9]\.)|(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:[1-9][0-9]\.)|(?:[0-9]\.)){3}(?:(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5])|(?:[1-9][0-9])|(?:[0-9]))$/;
            if (MOBILE_REGEXP.test(val) === true) {
                this.isShowbranch = false;
            }else {
                this.isShowbranch = true;
            }
        })
    }

    // 验证服务
    urlName() {
        const change = document.getElementById( 'urlName');
        const change$ = Observable.fromEvent(change, 'keyup').pluck('target', 'value').debounceTime(600);
        change$.subscribe((val: any)  => {
            let MOBILE_REGEXP = /^\/[a-zA-Z0-9]+$/;
            if (MOBILE_REGEXP.test(val) === true) {
                this.isSlash = false;
            }else {
                this.isSlash = true;
            }
        })
    }



}
